<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询用户名" v-model="username"></el-input>
      <el-button type="primary" @click="loadUsers(1)">查询</el-button>

      <el-button type="info" @click="resetSearch">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <el-table :data="usersData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="userid" label="用户ID" width="70" align="center"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="phone" label="电话"></el-table-column>
      <el-table-column prop="role" label="角色"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="del(scope.row.userid)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>
    <el-dialog title="用户信息" :visible.sync="dialogVisible" width="30%">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" placeholder="密码"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="电话"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="学生" value="user"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    return {
      usersData: [],  // 所有的用户数据
      pageNum: 1,    // 当前的页码
      pageSize: 10,  // 每页显示的个数
      username: '',
      total: 0,
      dialogVisible: false,
      form: {},
      selectedIds: [],
      rules: {
        // username: [
        //   { required: true, message: '请输入用户名', trigger: 'blur' },
        //   { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
        // ],
        // password: [
        //   { required: true, message: '请输入密码', trigger: 'blur' }
        // ],
        // name: [
        //   { required: true, message: '请输入姓名', trigger: 'blur' }
        // ],
        // phone: [
        //   { required: true, message: '请输入电话', trigger: 'blur' }
        // ],
        // role: [
        //   { required: true, message: '请选择角色', trigger: 'change' }
        // ]
      }
    };
  },
  created() {
    this.loadUsers();
  },
  methods: {
    delBatch() {
      if (!this.selectedIds.length) {
        this.$message.warning('请选择数据');
        return;
      }
      this.$confirm('您确认批量删除这些数据吗？', '确认删除', {type: "warning"}).then(() => {
        this.$request.post('/users/delete/batch', { ids: this.selectedIds }).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功');
            this.loadUsers(1);
          } else {
            this.$message.error(res.msg);
          }
        });
      }).catch(() => {});
    },
    handleSelectionChange(rows) {
      this.selectedIds = rows.map(v => v.userid);
    },
    del(userid) {
      this.$confirm('您确认删除吗？', '确认删除', {type: "warning"}).then(() => {
        this.$request.delete('/users/delete/' + userid).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功');
            this.loadUsers(1);
          } else {
            this.$message.error(res.msg);
          }
        });
      }).catch(() => {});
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝
      this.dialogVisible = true;
    },
    handleAdd() {
      this.form = {}; // 清空表单
      this.dialogVisible = true;
    },
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const url = this.form.userid ? '/users/update' : '/users/add';
          const method = this.form.userid ? 'PUT' : 'POST';
          this.$request({
            url: url,
            method: method,
            data: this.form,
            headers: {
              'Content-Type': 'application/json'
            }
          }).then(res => {
            if (res.code === '200') {
              this.$message.success('保存成功');
              this.loadUsers(1);
              this.dialogVisible = false;
            } else {
              this.$message.error(res.msg);
            }
          }).catch(error => {
            console.error('Request failed:', error);
            this.$message.error('保存失败，请重试。');
          });
        }
      });
    },
    resetSearch() {
      this.username = '';
      this.loadUsers();
    },
    handleCurrentChange(pageNum) {
      this.loadUsers(pageNum);
    },
    async loadUsers(pageNum) {
      const token = localStorage.getItem('token');

// 打印token到控制台
console.log(token);
      if (pageNum) this.pageNum = pageNum;
      try {
        const res = await this.$request.get('/users/selectByPage', {
          params: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            username: this.username
          }
        });
        this.usersData = res.data.records || [];
        this.total = res.data.total || 0;
      } catch (error) {
        console.error('请求用户数据失败', error);
        this.usersData = [];
        this.total = 0;
        this.$message.error('加载用户数据失败');
      }
    },
  },
};
</script>

<style scoped>
/* Add your CSS styles here */
</style>